/*****************************************************************************/
/**
 *  @file   InterfaceBase.h
 *  @author Allan Lorant, Naohisa Sakamoto
 */
/*----------------------------------------------------------------------------
 *
 *  Copyright (c) Visualization Laboratory, Kyoto University.
 *  All rights reserved.
 *  See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details.
 *
 *  $Id$
 */
/*****************************************************************************/
#ifndef INTERFACE_BASE_H
#define INTERFACE_BASE_H

#include <iostream>
#include <flowvr/module.h>


class InterfaceBase
{
private:

    flowvr::ModuleAPI* m_module;

public:

    InterfaceBase()
    {
        m_module = 0;
    }

    virtual ~InterfaceBase()
    {
        if ( m_module )
        {
            m_module->close();
            delete m_module;
        }
    }

    int init( const std::vector<flowvr::Port*>& ports )
    {
        m_module = flowvr::initModule( ports );
        return m_module == NULL ? -1 : 0;
    }

    int wait()
    {
        return m_module->wait();
    }

    flowvr::BufferWrite alloc( size_t size )
    {
        return m_module->alloc( size );
    }

    int get( flowvr::InputPort* input_port, flowvr::Message& message )
    {
        return m_module->get( input_port, message );
    }

    int get( std::string input_portname, flowvr::Message& message )
    {
        flowvr::Port* port = m_module->getPortByName( input_portname );
        if ( !port )
        {
            std::cerr << "Can't find an input port '" << input_portname << "'." << std::endl;
            return -1;
        }

        if ( !port->isInput() )
        {
            std::cerr << "'" << input_portname << "' isn't an input port." << std::endl;
            return -1;
        }

        flowvr::InputPort* input_port = static_cast<flowvr::InputPort*>( port );
        return this->get( input_port, message );
    }

    int put( flowvr::OutputPort* output_port, flowvr::MessageWrite& message )
    {
        return m_module->put( output_port, message );
    }

    int put( std::string output_portname, flowvr::MessageWrite& message )
    {
        flowvr::Port* port = m_module->getPortByName( output_portname );
        if ( !port )
        {
            std::cerr << "Can't find an output port '" << output_portname << "'." << std::endl;
            return -1;
        }

        if ( !port->isOutput() )
        {
            std::cerr << "'" << output_portname << "' isn't an output port." << std::endl;
            return -1;
        }

        flowvr::OutputPort* output_port = static_cast<flowvr::OutputPort*>( port );
        return this->put( output_port, message );
    }
};

#endif
